package com.xiaomi.shoppinglist

import android.appwidget.AppWidgetManager
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class AddItemActivity : AppCompatActivity() {
    private val TAG = "AddItemActivity"
    private var isRepeatable = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.add_item_activity)

        // 初始化数据库
        ShoppingListDatabase.init(this)

        // 设置类型选择监听器
        val itemTypeGroup = findViewById<RadioGroup>(R.id.item_type_group)
        val repeatSettings = findViewById<LinearLayout>(R.id.repeat_settings)

        itemTypeGroup.setOnCheckedChangeListener { _, checkedId ->
            isRepeatable = checkedId == R.id.repeatable_radio
            repeatSettings.visibility = if (isRepeatable) LinearLayout.VISIBLE else LinearLayout.GONE
        }

        // 设置保存按钮点击事件
        findViewById<Button>(R.id.save_button).setOnClickListener {
            saveItem()
        }
    }

    private fun saveItem() {
        val itemName = findViewById<EditText>(R.id.item_name_input).text.toString().trim()

        if (itemName.isEmpty()) {
            Toast.makeText(this, "请输入购物项名称", Toast.LENGTH_SHORT).show()
            return
        }

        val item = ShoppingItem(
            name = itemName,
            isCompleted = false,
            isRepeatable = isRepeatable,
            createTime = System.currentTimeMillis()
        )

        if (isRepeatable) {
            val intervalInput = findViewById<EditText>(R.id.interval_input)
            val intervalUnitSpinner = findViewById<Spinner>(R.id.interval_unit_spinner)

            val interval = intervalInput.text.toString().toIntOrNull() ?: 1
            val unit = intervalUnitSpinner.selectedItemPosition

            item.reminderInterval = interval
            item.reminderUnit = unit
        }

        // 保存购物项
        val db = ShoppingListDatabase.getInstance(this)
        db.shoppingItemDao().insert(item)

        Log.d(TAG, "Item saved: $item")

        // 更新小部件
        updateWidgets()

        // 关闭活动
        finish()
    }

    private fun updateWidgets() {
        val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE)
        sendBroadcast(intent)
    }
}